home *** CD-ROM | disk | FTP | other *** search
- Path: EU.net!sun4nl!xs4all!falstaff
- From: falstaff@xs4all.nl (Falstaff)
- Newsgroups: comp.lang.c
- Subject: Re: Determining the length of an int in string form
- Date: 14 Mar 1996 17:13:01 GMT
- Organization: XS4ALL, networking for the masses
- Message-ID: <4i9k2t$m6p@news.xs4all.nl>
- References: <3146D058.DD7@cbm.com>
- NNTP-Posting-Host: xs1.xs4all.nl
- X-Newsreader: NN version 6.5.0 #666 (NOV)
-
- Dave Payne <paynedc@cbm.com> writes:
-
- >Consider this:
-
- >I have a variable of type int, and I would like to use the sprintf()
- >function to write this variable to a string. However, I want to
- >dynamically allocate the space for the string, and only malloc enough
- >space to hold the int. Here's a code fragment that may illustrate this
- >more clearly:
-
- >void func1() {
-
- > int i = 1234;
- > char *a;
-
- > a = malloc(strlen("The value of i is ") + 4 + 1);
- > sprintf(a,"%s%d","The value of i is ",i);
-
- Nasty programming here -- what if you change one string and not the
- other?
-
- >In this example, I hardcoded the 4, because I knew that 1234 was 4
- >characters long. I would like to be able to determine this at runtime,
- >and malloc enough space accordingly.
-
- Why?
-
- In one recent case I needed something like this too and used strdup()
- on the result of a sprintf().
-
- Of course, your *original* question is answered by
-
- int length_of_decimal(unsigned n)
- { int i=1;
-
- do
- { n/=10;
- i++;
- } while(n);
-
- return i;
- }
-
- Frank
- --
- The famous GIICM now on line: http://www.xs4all.nl/~falstaff/GIICM.html
- ------------------------------------------------------------------------
- Frank A. Vorstenbosch +31-(70)-355 5241 falstaff@xs4all.nl
-